import 'package:flutter/material.dart';
import 'package:proj_sfv/domain/Comment.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:expandable/expandable.dart';

class CommentPopup extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _CommentPopup();
  var _videoId;
  int id;
  String token;

  CommentPopup(this._videoId, this.id, this.token);
}

class _CommentPopup extends State<CommentPopup> {
  bool _currentOrder = true; // true为热度排序
  TextEditingController _controller = TextEditingController();
  String hintText = "发表评论";
  CommentTree tree = CommentTree.empty();
  CommentTreeNode _focusComment;
  List<bool> _showChildren = [];


  @override
  void initState() {
    super.initState();
    getVideoCommentTreeRequest(context, widget._videoId).then((value) async {
      if (value != null) {
        if (value.commentTreeNodes.isNotEmpty) {
          List<int> commentIds = [];
          List<int> userIds = [];
          for (var element in value.commentTreeNodes) { commentIds.add(element.commentId);userIds.add(element.authorId); }
          var resp2 = await getCommentIsLikeRangeRequest(context, commentIds, widget.token, value.videoId, widget.id);
          var resp3 = await getCommentIsLikeRangeRequest(context, commentIds, widget.token, value.videoId, widget.id,
              type: CommentPreference.DISLIKE);
          var resp4 = await getUserProfileRangeRequest(context, userIds, widget.token);
          if (resp2 != null && resp3 != null) {
            for (int i = 0; i < value.commentTreeNodes.length; ++i) {
              var item = value.commentTreeNodes[i];
              item.isLike = resp2[i];
              item.isDislike = resp3[i];
              item.userProfile = Uri.https(cosHost, '${resp4[item.authorId].profile}.jpg').toString();
            }
          }
          if (resp4 != null) {
            for (var element in value.commentTreeNodes) {
              element.userName = resp4[element.authorId].userName;
              element.userProfile = Uri.https(cosHost, '${resp4[element.authorId].profile}.jpg').toString();
            }}
        }
        setState(() {
          tree = value;
          _showChildren = List.filled(tree.commentTreeNodes.length, false, growable: true);
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var theme = Theme.of(context);
    var style = theme.textTheme.bodyLarge?.copyWith(color: Colors.grey);
    return WillPopScope(
      onWillPop: () async {return false;},
      child: SizedBox(
        height: 500,
        child: Column(
          children: [
            SizedBox(
              height: 35,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    // Text(_currentOrder ? "热门评论" : "最新评论", style: style,),
                    // TextButton(onPressed: () {
                    //   setState(() {
                    //     _currentOrder = !_currentOrder;
                    //   });
                    // }, child: Text(_currentOrder ? "按时间排序" : "按热度排序"))
                  ],
                ),
            ),
            const Divider(thickness: 1,),
            Expanded(
                child: tree == null ? Container() : ListView.builder(
                    itemCount: tree.commentTreeNodes.length,
                    itemBuilder: (context, index) {
                      var item = tree.commentTreeNodes.elementAt(index);
                      ExpandableController controller = ExpandableController(initialExpanded: false);
                      var root = CommentItem(
                          item,
                          _focusComment == null ? false : (_focusComment.commentId == item.commentId),
                              () {
                            setState(() {
                              _focusComment = item;
                            });
                          },
                          () async {
                            if (!_showChildren[index]) {
                              var resp = await getVideoCommentTreeChildRequest(context, widget._videoId, item.commentId);
                              if (resp != null) {
                                if (resp.isNotEmpty) {
                                  List<int> commentIds = [];
                                  List<int> userIds = [];
                                  for (var element in resp) { commentIds.add(element.commentId); userIds.add(element.authorId); }
                                  var resp2 = await getCommentIsLikeRangeRequest(context, commentIds, widget.token, widget._videoId, widget.id);
                                  var resp3 = await getCommentIsLikeRangeRequest(context, commentIds, widget.token, widget._videoId, widget.id,
                                      type: CommentPreference.DISLIKE);
                                  var resp4 = await getUserProfileRangeRequest(context, userIds, widget.token);
                                  if (resp2 != null && resp3 != null && resp4 != null) {
                                    for (int i = 0; i < resp.length; ++i) {
                                      resp[i].isLike = resp2[i];
                                      resp[i].isDislike = resp3[i];
                                      resp[i].userName = resp4[resp[i].authorId].userName;
                                      resp[i].userProfile = Uri.https(cosHost, '${resp4[resp[i].authorId].profile}.jpg').toString();
                                    }
                                  }
                                }
                                setState(() {
                                  item.child = resp;
                                  controller.expanded = true;
                                  _showChildren[index] = true;
                                });
                              }
                            } else {
                              setState(() {
                                setState(() {
                                  _showChildren[index] = false;
                                });
                              });
                            }
                          },
                          (CommentOpsType type) async {
                              var result = await commentOperateRequest(context, widget.id,
                                  widget.token, widget._videoId, item.commentId, ops: type);
                              if (result!=null) {
                                return "success";
                              } else {
                                return "fault";
                              }
                          },
                          (CommentOpsType type) async {
                            var result = await commentOperateRequest(context, widget.id,
                                widget.token, widget._videoId, item.commentId, preference: CommentPreference.DISLIKE, ops: type);
                            if (result!=null) {
                              return "success";
                            } else {
                              return "fault";
                            }
                          }
                      );
                      return Column(
                        children: [
                          root,
                          _showChildren[index] ? FutureBuilder(builder: (context, snapshot) {
                            return Padding(
                              padding: EdgeInsets.only(left: 10, top: 10),
                              child: Column(
                                children: item.child.isNotEmpty ? item.child.map((e) =>
                                    CommentItem(e,
                                      false, null, null,
                                          (CommentOpsType type) async {
                                        var result = await commentOperateRequest(context, widget.id,
                                            widget.token, widget._videoId, e.commentId, ops: type);
                                        if (result!=null) {
                                          return "success";
                                        } else {
                                          return "fault";
                                        }
                                      },
                                          (CommentOpsType type) async {
                                        var result = await commentOperateRequest(context, widget.id,
                                            widget.token, widget._videoId, e.commentId, preference: CommentPreference.DISLIKE, ops: type);
                                        if (result!=null) {
                                          return "success";
                                        } else {
                                          return "fault";
                                        }
                                      },
                                      isRoot: false,
                                    )
                                ).toList() : [Center(child: ListTile( title: Text("没有更多子评论了"),))]
                              ),
                            );
                          }) : Container()
                        ],
                      );
                    },
                )
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                color: Colors.grey[200],
                child: Padding(
                  padding: EdgeInsets.all(8),
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(
                      hintText: hintText,
                      prefix: _focusComment != null ? InputChip(
                          label: Text("追评@${_focusComment.authorId}"),
                          onDeleted: () {
                            setState(() {
                              _focusComment = null;
                            });
                        },
                      ) : null,
                      border: InputBorder.none,
                      suffixIcon: IconButton(
                        icon: Icon(Icons.send),
                        onPressed: () async {
                          // 在这里可以处理输入框中的内容
                          String content = _controller.text.trim();
                          if (_focusComment == null) {
                            var data = await publishCommentRequest(context, widget.id, widget.token, widget._videoId, content);
                            var resp2 = await getBasicMyRequest(context, widget.id, widget.token);
                            if (data != null) {
                              if (resp2 != null) {
                                data.userName = resp2.userName;
                                data.userProfile = resp2.profile;
                              }
                              setState(() {
                                _controller.clear();
                                _showChildren.add(false);
                                tree.commentTreeNodes.add(data);
                              });
                            }
                          } else {
                            var data = await publishCommentRequest(context, widget.id, widget.token,
                                widget._videoId, content, parentId: _focusComment.commentId);
                            var resp2 = await getUserDetailInfoRequest(context, widget.token, widget.id);
                            if (data != null) {
                              if (resp2 != null) {
                                data.userName = resp2.userName;
                                data.userProfile = resp2.profile;
                              }
                              setState(() {
                                _controller.clear();
                                _focusComment.child.add(data);
                                _focusComment = null;
                              });
                            }
                          }
                        },
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  _CommentPopup();
}

class CommentItem extends StatefulWidget {
  // int authorId;
  // String content;
  // int likeCount;
  // int commentId;
  // DateTime commentTime;
  // bool isDeleted;
  // int replyId;
  //
  // bool _isLike;
  // bool _isDislike;
  bool _isFocus;

  var reply;
  var getComentImpl;
  var likeCommentImpl;
  var dislikeCommentImpl;

  CommentTreeNode node;
  bool isRoot;

  CommentItem( this.node,
      this._isFocus, this.reply, this.getComentImpl, this.likeCommentImpl, this.dislikeCommentImpl ,{bool isRoot = true}) :
        this.isRoot = isRoot;

  @override
  State<CommentItem> createState() => _CommentItemState();
}

class _CommentItemState extends State<CommentItem> {
  ExpandableController _controller = ExpandableController(initialExpanded: false);
  bool _isShowChild = false;

  @override
  Widget build(BuildContext context) {
    var theme = Theme.of(context).textTheme;
    var authorNameStyle = theme.bodyMedium?.copyWith(color: Colors.pink);
    var timeStyle = theme.bodySmall?.copyWith(color: Colors.grey);
    var contentStyle = theme.bodyMedium?.copyWith(fontWeight: FontWeight.bold);
    return Container(
      decoration: BoxDecoration(
        border: widget.isRoot ? Border.all(
          color: Colors.black12,
          width: 1
        ) : Border(bottom: BorderSide(color: Colors.black26, width: 1))
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              SizedBox(
                height: widget.isRoot ? 60 : 40,
                child: CircleAvatar(
                  radius: widget.isRoot ? 40 : 30,
                  backgroundImage: NetworkImage(widget.node.userProfile ?? ""),
                ),
              ),
              SizedBox(width: 10,),
              Column(
                children: [
                  Text(widget.node.userName ?? widget.node.authorId.toString(), style: authorNameStyle, textAlign: TextAlign.left,),
                  widget.node.commentTime == null ? Text("") : Text(widget.node.commentTime.toIso8601String().substring(0, 10), style: timeStyle,),
                ],
              ),
            ],
          ),
          Padding(
            padding: widget.isRoot ? const EdgeInsets.only(left: 100, top: 5, right: 10) :
              EdgeInsets.only(left: 80, top: 3, right: 10),
            child: SizedBox(
                height: null,
                child: ExpandableNotifier(
                  controller: _controller,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Expandable(
                            collapsed: Text(widget.node.content, maxLines: 3,
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                            ),
                            expanded: Text(widget.node.content),
                          controller: _controller,
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerLeft,
                        child: TextButton(onPressed: () {
                          _controller.toggle();
                          setState(() {
                          });
                        }, child: Text(_controller.expanded ? "收起" : "显示更多")),
                      )
                    ],
                  ),
                )
            ),
          ),
          widget.isRoot ? Padding(
            padding: const EdgeInsets.only(left: 50, top: 8),
            child: TextButton(
                onPressed: () async {
                    await widget.getComentImpl();
                    setState(() {
                      _isShowChild = !_isShowChild;
                    });
                },
                child: _isShowChild ? Text("收起") : Text("展开更多回复")
            ),
          ) : SizedBox(height: 0,),
          ButtonBar(
            buttonPadding: EdgeInsets.all(1),
            buttonMinWidth: 20,
            children: [
              MaterialButton(
                onPressed: () async {
                  String result = await widget.likeCommentImpl(widget.node.isLike ? CommentOpsType.CANCEL : CommentOpsType.SET);
                  if (result == "success") {
                    setState(() {
                      widget.node.isLike = !widget.node.isLike;
                      if (widget.node.isLike) {
                        widget.node.likeCount++;
                      } else {
                        widget.node.likeCount--;
                      }
                    });
                  }
                },
                child:
                Row(
                  children: [
                    Icon(Icons.thumb_up_alt_outlined, color: (widget.node.isLike ?? false) ? Colors.red : Colors.black38,),
                    SizedBox(width: 3,),
                    Text(widget.node.likeCount.toString())
                  ],
                ),),
              MaterialButton(
                onPressed: () async {
                  String result = await widget.dislikeCommentImpl(widget.node.isDislike ? CommentOpsType.CANCEL : CommentOpsType.SET);
                  if (result == "success") {
                    setState(() {
                      widget.node.isDislike = !widget.node.isDislike;
                    });
                  }
                },
                  child: Icon(Icons.thumb_down_alt_outlined, color: (widget.node.isDislike ?? false) ? Colors.red : Colors.black38),
              ),
              widget.isRoot ? MaterialButton(
                  onPressed: () {
                    widget.reply();
                  },
                  child: Icon(Icons.message_outlined, color: widget._isFocus ? Colors.red : Colors.black38),
              ) : Container(),
            ],
          ),
        ],
      ),
    );
  }
}